package com.tbit.uqbike.tergateway.wa206pkg;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tbit.uqbike.TerGatewayMain;
import com.tbit.uqbike.protocol.ATerPkg;
import com.tbit.uqbike.protocol.AnalyzeImpl.AProtocol;
import com.tbit.uqbike.protocol.AnalyzeImpl.WA206DeEnCoder;
import com.tbit.uqbike.tergateway.config.TerGatewayConfig;
import com.tbit.uqbike.tergateway.entity.AConnInfo;
import com.tbit.uqbike.util.ConstDefine;
import com.tbit.uqbike.util.StringUtil;
import io.netty.buffer.ByteBuf;

import java.util.*;

/**
 * @author MyWin E-mail:335918956@qq.com
 * @version 1.0
 * @createTime 2019/2/26 0026 11:06
 */
public class TerStatusChange extends ATerPkg {
    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TerStatusChange.class);
    @JSONField(name = "时间", format = "yyyy-MM-dd HH:mm:ss")
    public Date dt;
    @JSONField(name = "变更列表")
    public List<TerStatusChangeItem> changeItemList;

    @Override
    public void doBusiness() {
        logger.debug(this.toString());
        // 推送给公共平台
        TerGatewayMain.getProducer().sendDataToQueue(TerGatewayConfig.terStatusChange, getPushData(getTerStatusChangeEntry()));
    }

    public static class TerStatusChangeEntry {
        public String sn;
        public Date dt;
        public List<TerStatusChangeItem> changeItemList;
    }

    public TerStatusChangeEntry getTerStatusChangeEntry() {
        TerStatusChangeEntry tsce = new TerStatusChangeEntry();
        tsce.sn = this.mno;
        tsce.dt = this.dt;
        tsce.changeItemList = new LinkedList<>();
        tsce.changeItemList.addAll(this.changeItemList);
        return tsce;
    }

    public static String getPushData(TerStatusChangeEntry statusChange) {
        Map<String, Object> valueMap = new HashMap<>();
        valueMap.put("msgId", ConstDefine.MQ_MSG_ID_STATUS_CHANGE_PUSH);
        valueMap.put("feedback", StringUtil.Empty);
        valueMap.put("data", statusChange);
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(valueMap);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    public boolean autoRsp() {
        return true;
    }

    @Override
    public ByteBuf getRsp(AConnInfo conn, AProtocol protocol) {
        return ((WA206DeEnCoder) protocol).getStatusChangeRsp(conn, this);
    }
}
